package com.mystudy.leetcode.problem.tree.p_589;

import com.mystudy.leetcode.base.Node;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @program: infoalgorithm
 * @description: N叉树的前序遍历
 * @author: zhouzhilong
 * @create: 2019-07-23 15:42
 **/
public class Solution {

    /**
     * 非递归遍历,速度比较慢
     *
     * @param root
     * @return
     */
    public List<Integer> preorder(Node root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Stack<Node> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node cur = stack.pop();
            list.add(cur.val);

            List<Node> childrens = cur.children;
            for (int i = childrens.size() - 1; i >= 0; i--) {
                Node children = childrens.get(i);
                stack.push(children);
            }
        }
        return list;
    }


    /**
     * 递归方式,速度更快
     *
     * @param root
     * @return
     */
    public List<Integer> preorder2(Node root) {
        List<Integer> list = new ArrayList<>();
        preorder(root, list);
        return list;
    }

    private void preorder(Node node, List<Integer> list) {
        if (node == null) {
            return;
        }
        list.add(node.val);
        List<Node> childrens = node.children;
        for (int i = 0; i < childrens.size(); i++) {
            preorder(childrens.get(i), list);
        }
    }
}
